package com.masterclient.app.base;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselibrary.utils.NetworkingUtil;
import com.eoner.baselibrary.widget.PermissionDialog;
import com.masterclient.app.BaseActivity;
import com.masterclient.app.R;
import com.masterclient.app.modules.bridge.BridgeActivity;
import com.masterclient.app.modules.main.beans.ScanDataBean;
import com.masterclient.app.modules.main.beans.ScanWelfareBean;
import com.masterclient.app.modules.main.contract.ScanContract;
import com.masterclient.app.modules.main.contract.ScanPresenter;
import com.masterclient.app.modules.main.manager.ScanManager;
import com.masterclient.app.utils.CommonUtil;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.uuzuche.lib_zxing.activity.CaptureFragment;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class CaptureActivity extends BaseActivity<ScanPresenter> implements ScanContract.View {

    @BindView(R.id.capture_back)
    LinearLayout captureBack;
    @BindView(R.id.capture_content)
    FrameLayout captureContent;
    @BindView(R.id.capture_pic)
    LinearLayout capturePic;

    private boolean isHome = false;
    private String eventId;
    private String code;
    private RxPermissions rxPermissions;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_capture);
        ButterKnife.bind(this);

        isHome = getIntent().getBooleanExtra("isHome", false);
        eventId = getIntent().getStringExtra("eventId");
        rxPermissions = new RxPermissions(this);
        CaptureFragment captureFragment = new CaptureFragment();
        captureFragment.setAnalyzeCallback(analyzeCallback);
        getSupportFragmentManager().beginTransaction().replace(R.id.capture_content, captureFragment).commit();


        capturePic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean hasPermissions = rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                if (!hasPermissions) {
                    new PermissionDialog(CaptureActivity.this, "开启相册权限", "获取相册权限以便图片扫码，请在下一个页面点击“允许”",
                            R.mipmap.icon_permission_storage, () -> {
                        Intent intent = new Intent(CaptureActivity.this, ImageGridActivity.class);
                        startActivityForResult(intent, 100);
                    }).show();
                } else {
                    Intent intent = new Intent(CaptureActivity.this, ImageGridActivity.class);
                    startActivityForResult(intent, 100);
                }
            }
        });

        captureBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && requestCode == 100) {
            if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
                CodeUtils.analyzeBitmap(((ArrayList<ImageItem>) data.getSerializableExtra(
                        ImagePicker.EXTRA_RESULT_ITEMS)).get(0).path, analyzeCallback);
            }
        }
    }

    /**
     * 二维码解析回调函数
     */
    CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {
        @Override
        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
            if (!TextUtils.isEmpty(eventId)){
                //扫码签到
                mPresenter.scanSign(eventId,result);
            }else {
                if (isHome) {
                    CommonUtil.goAnyWhere(mContext, result, "", "", "", "", "");
                } else {
                    Intent intent = new Intent();
                    intent.putExtra("result", result);
                    setResult(3, intent);
                }
                finish();
            }
        }

        @Override
        public void onAnalyzeFailed() {
            Toast.makeText(CaptureActivity.this, "二维码太小或没有找到二维码，请重新拍摄", Toast.LENGTH_LONG).show();
            CaptureActivity.this.finish();
        }
    };

    Map<String, String> map = new HashMap<>();

    @Override
    public void showData(ScanDataBean data) {
        map.clear();
        map.put("target", data.getTarget());
        map.put("target_id", data.getTarget_id());
        if (!data.getTarget().startsWith("http")) {
            mPresenter.getDialogData(code);
        } else {
            CommonUtil.goAnyWhereBundle(this, map);
            finish();
        }
    }

    @Override
    public void showDialogData(ScanWelfareBean scanWelfareBean) {
        map.put("code", code);
        ScanManager.getScanManager().welfareBean = scanWelfareBean;
        ScanManager.getScanManager().code = code;
        CommonUtil.goAnyWhereBundle(this, map);
        finish();
    }

    @Override
    public void scanSignSuccess() {
        ToastUtil.showToast("签到成功");
    }

    @Override
    public void scanSignFail(String s) {
        ToastUtil.showToast(s);
    }

    @Override
    public void loadFail(String s) {
        ToastUtil.showToast(s);
        finish();
    }

}
